package com.org.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;



public class FileUploadOrDown  {
	private static final long serialVersionUID = -7744625344830285257L;
	/**
	 * 图片上传到服务器
	 * @param name 图片名字
	 * @param url 图片地址
	 * @param file  图片流
	 * @return
	 */
	public String upToServer(String name, String url, InputStream input,String pre) {
		String path;
		String imgurl = "";
		try {
			path = this.getClass().getResource("/").toURI().getPath();
			path = path.substring(0, path.length() - 17);
			path = path.substring(0,path.lastIndexOf("/")+1) + "tupian";
			imgurl = pre + url + "/";
			File f = new File(path + imgurl);
			if (!f.exists()) {
				f.mkdirs();
			}
			FileOutputStream output = new FileOutputStream(path + imgurl + name);
			int read = input.read();
			while (read != -1) {
				output.write(read);
				read = input.read();
			}
			input.close();
			output.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "../../tupian"+imgurl + name;
	}
	
	/**
	 * 删除服务器文件及文件夹
	 * @param path 数据库存放路径
	 * @throws Exception
	 */
	public void deleteServerFiles(String path) throws Exception {
		String pathclass = this.getClass().getResource("/").toURI().getPath();
		pathclass = pathclass.substring(0, pathclass.length() - 17);
		path =pathclass+path.substring(9,path.length());
		File file = new File(path);
		// 1级文件删除
		if (!file.isDirectory()) {
			file.delete();
		} else if (file.isDirectory()) {
			// 2级文件列表
			String[] filelist = file.list();
			// 获取新的二级路径
			for (int j = 0; j < filelist.length; j++) {
				File filessFile = new File(path + "\\" + filelist[j]);
				if (!filessFile.isDirectory()) {
					filessFile.delete();
				} else if (filessFile.isDirectory()) {
					// 递归调用
					deleteServerFiles(path + "\\" + filelist[j]);
				}
			}
			file.delete();
		}
	}
}
